package com.bclz.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class NioFileChannelExample {


    public static void main(String[] args) throws IOException {

//        write();
//        read();

//        commonBufferTransfer();

        //直接用transferFrom 复制
        FileInputStream inputStream=new FileInputStream("F:\\客户端宫格&视频操作手册.zip");
        File file=new File("F:\\客户端宫格&视频操作手册Copy.zip");
        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream outputStream = new FileOutputStream(file);
        FileChannel inputStreamChannel = inputStream.getChannel();
        FileChannel outputStreamChannel = outputStream.getChannel();
        outputStreamChannel.transferFrom(inputStreamChannel,0,inputStreamChannel.size());
        inputStreamChannel.close();
        outputStreamChannel.close();
        inputStream.close();
        outputStream.close();
    }


    public static void commonBufferTransfer() throws IOException {

        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        FileInputStream inputStream=new FileInputStream("F:\\客户端宫格&视频操作手册.zip");
        FileChannel inputStreamChannel = inputStream.getChannel();
        File file=new File("F:\\客户端宫格&视频操作手册Copy.zip");
        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream outputStream = new FileOutputStream(file);
        FileChannel outputStreamChannel = outputStream.getChannel();
        while(inputStreamChannel.read(byteBuffer)>0){
            //写到缓冲区后反转
            byteBuffer.flip();
            //缓冲区到输出通道
            outputStreamChannel.write(byteBuffer);
            //清空缓冲区
            byteBuffer.clear();
        }
        inputStreamChannel.close();
        outputStreamChannel.close();
        inputStream.close();
        outputStream.close();

    }

    public static void write() throws IOException{

        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        byteBuffer.put("hello,世界".getBytes(Charset.forName("UTF-8")));
        //反转缓冲区
        byteBuffer.flip();
        File file=new File("E:/test.txt");
        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream outputStream=new FileOutputStream(file);
        FileChannel fileChannel=outputStream.getChannel();
        fileChannel.write(byteBuffer);
        outputStream.close();

    }

    public static void read() throws IOException {

        File file=new File("E:/test.txt");
        FileInputStream inputStream=new FileInputStream(file);
        //获取Channel
        FileChannel channel = inputStream.getChannel();
        //创建缓存区
        ByteBuffer byteBuffer=ByteBuffer.allocate((int)file.length());
        //读取Channel数据到缓冲区
        channel.read(byteBuffer);
        System.out.println(new String(byteBuffer.array()));
        inputStream.close();
    }

}
